home *** CD-ROM | disk | FTP | other *** search
- Path: max.tiac.net!craigm
- From: craigm@max.tiac.net (Craig Mattson)
- Newsgroups: comp.lang.c
- Subject: Intraprocess piping into an array
- Date: 6 Apr 1996 22:26:01 GMT
- Organization: The Internet Access Company
- Message-ID: <4k6r1p$eoh@news.tiac.net>
- NNTP-Posting-Host: max.tiac.net
-
- I'd like to pipe stdout into an array so I can process it before
- it actually gets printed. However, I don't want to fork a process
- just to read the array as it's being output. Here's what I've been
- trying to do, which works until the output gets too large:
-
-
- int pipefds[ 2 ];
- int real_stdout;
- char stdout_buf[ HUGE_BUFFER ];
- char output_buffer[ 1024 ];
- FILE *fp;
-
- int pipefds[2];
- if( pipe(pipefds) <0) {
- perror( "pipe" );
- exit( 1 );
- }
-
- int real_stdout = dup( 1 );
- close( 1 );
- dup( pipefds[0] );
- close( pipefds[0] );
-
- /*
- * create a huge buffer for the new stdout so fputs(,stdout) doesn't
- * block when trying to write more than the standard buffer size
- */
- setvbuf( stdout, stdout_buf, _IOFBF, MAX_HTML_LENGTH );
-
- /*
- * call stuff that writes to stdout here (e.g. printf(), fputs() )
- */
-
- /*
- * now set stdout back to its real output
- */
- fflush( stdout ); /* Here's my problem */
- close( 1 );
- dup( real_stdout );
- close( real_stdout );
- fp = fdopen( pipefds[1], "r" );
-
- /*
- * read from fp to do whatever
- */
-
- fclose( fp );
-
- The problem is that the fflush() tries to flush the _whole_ buffer,
- which is often too large for the standard buffer size for the read end
- of the pipe. So it blocks until the other end of the pipe clears out
- some space, which of course doesn't happen because there's no other
- process involved.
-
- I tried calling fdopen() for the read side before calling fflush() and
- using setvbuf() to make the read buffer bigger like I do for the write
- side. This doesn't seem to solve the problem.
-
- I don't really need to use the stdio library to read from the pipe. Is
- it safe to just examine the stdout_buf array I'm using directly? If so,
- how do I just kill the pipe so that when I exit() it doesn't try to
- close it for me and end up blocking there? Alternatively, can I increase
- the size of the buffer used by the file descriptors created by pipe()?
- Can I somehow flush just part of the array at a time?
-
- I'm certain other people have thought about this problem, and there may
- be some standard approach for how to do this. Any education you could
- offer me would be greatly appreciated. Email is better for me that the
- newsgroup, but I should get it either way.
-
- Thanks,
-
- Craig
-
-
-